package org.wz.complex.work.interceptor;


import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.wz.complex.work.entity.auth.token.TokenPclogin;
import org.wz.complex.work.kit.encrypt.TokenKit;
import org.wz.complex.work.service.auth.token.TokenPcloginService;

@Component
public class UserLoginInterceptor implements HandlerInterceptor {

    @Resource
    private TokenPcloginService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从session中获取用户信息
        // HttpSession session = request.getSession();

        String token = TokenKit.hanleToken(request);
        if (null != token) {
            JWT jwt = JWTUtil.parseToken(token);
            Long userId = jwt.getPayloads().getLong("userId");
            System.out.println(userId);
            // token 查找
            LambdaQueryWrapper<TokenPclogin> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TokenPclogin::getUserId, userId);
            wrapper.eq(TokenPclogin::getStatus, 1);
            long count = tokenService.count(wrapper);
            return count == 1;
        }

        // 用户信息不存在，重定向到登录页面
        throw new RuntimeException("请登录");

    }

}